/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.usecase.editpart;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.CreateConnectionRequest;

import com.cea.papyrus.core.commands.connection.ConnectionCreateCommand;
import com.cea.papyrus.core.helper.ModelerHelper;
import com.cea.papyrus.core.pseudoelement.EnhancedType;
import com.cea.papyrus.core.pseudoelement.UMLElementFactory;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;

/**
 * Policy for connection creation.
 * Redefines the common policy for association creation in this diagram.
 */
public class GraphNodeEditPolicy extends com.cea.papyrus.core.editpart.GraphNodeEditPolicy {

	/* (non-Javadoc)
	 * @see com.cea.papyrus.common.editpart.GraphNodeEditPolicy#getConnectionCreateCommand(org.eclipse.gef.requests.CreateConnectionRequest)
	 */
	@Override
	protected Command getConnectionCreateCommand(CreateConnectionRequest request) {
		// specifies the ConnectioncreateCommandFactory to be a usecase ConnnectionCreateCommandFactory
		Class type;
		Object newObjectDescription = EnhancedType.getNewObjectDescription(request);

		if (!(getHost().getModel() instanceof GraphNode)) {
			return null;
		}

		GraphNode source        = (GraphNode) getHost().getModel();

		// Test creation restriction in Connector creation
		// (due to filters defined in PaletteMenu extension
		boolean noRestriction = true;
		if (newObjectDescription instanceof UMLElementFactory) {
			UMLElementFactory enhancedType = (UMLElementFactory) newObjectDescription;
			type          = enhancedType.getClazz();
			noRestriction = enhancedType.canExecute(source);
		} else {
			type = (Class)  newObjectDescription;
		}
		
		Point location = computeAnchorLocation(request.getLocation(), getHost());

		if(source.getSemanticModel()!=null &&ModelerHelper.getFactory().canConnect(type, ((Uml1SemanticModelBridge)source.getSemanticModel()).getElement(),null) && noRestriction) {
			ConnectionCreateCommand cmd = com.cea.papyrus.diagram.usecase.command.ConnectionCreateCommandFactory.eINSTANCE.getConnectionCreateCommand(source, newObjectDescription, location);
			request.setStartCommand(cmd);
			return cmd;
		}
		return null;
	}
}